from drf_yasg import openapi
from drf_yasg.utils import swagger_auto_schema
from rest_framework import viewsets, status
from rest_framework.decorators import action
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from erp_system.models import MenuModel
from erp_system.serializer.menu_serializer import MenuSerializer
import logging

# 查看logging 是不是生效
logger = logging.getLogger('erp')

"""
    功能菜单的模型类
    1.新增
    2.查询单个功能
    3.查询所有功能菜单 1
    4.查询某个父内菜单下面的所有子菜单列表 1
    5.查询顶级菜单列表1
    6.删除某个功能菜单
    7.批量删除多个菜单 参书【1,2,3】 1
    8.修改功能菜单
    """


class MenuView(viewsets.ModelViewSet):
    """
    create:
    创建菜单
    retrieve:
    查询单个菜单
    update:
    全局修改菜单
    partial_update:
    局部修改菜单
    destroy:
    删除用户菜单，这里删除是指把delete_flag=1
    list:
    查询所有菜单
    """
    # permission_classes = (IsAuthenticated,)
    queryset = MenuModel.objects.filter(delete_flag=0).all()
    serializer_class = MenuSerializer

    def get_queryset(self):
        # logger.info(f"当前用户是:{self.request.user.username}")
        """
        两种情况
        1.查询所有菜单列表，不要传任何参数
        2.查询父菜单下面的所有子菜单，需要传递一个参数，名字较pid，pid==0时候，查询所有父菜单
        """
        query_param = self.request.query_params.get('pid', None)
        if query_param:
            pid = int(query_param)
            if pid == 0:  # 查询所有顶级列表
                return MenuModel.objects.filter(parent__isnull=True, delete_flag=0).all()
            else:  # 查询所有子列表
                return MenuModel.objects.filter(parent__id=pid, delete_flag=0).all()
        else:
            return MenuModel.objects.filter(delete_flag=0).all()

    def destroy(self, request, *args, **kwargs):
        # 这里的删除不是真正意义上的删除 是修改delete_flag=1
        menu = self.get_object()
        menu.delete_flag = '1'
        menu.save()
        # 可能下面还有很多的子菜单，所以我们也要修改值
        MenuModel.objects.filter(parent__id=menu.id).update(delete_flag=1)
        return Response(status=status.HTTP_204_NO_CONTENT)

    del_ids = openapi.Schema(type=openapi.TYPE_OBJECT, required=['ids'], properties={
        'ids': openapi.Schema(type=openapi.TYPE_ARRAY, items=openapi.Schema(type=openapi.TYPE_INTEGER),
                              description="选择要删除那些需要删除的ID（主键）列表")
    })

    @swagger_auto_schema(methods=['delete'], request_body=del_ids, operation_description="批量删除")
    @action(methods=['DELETE'], detail=False)
    def multiple_delete(self, request, *args, **kwargs):
        # 传入的数据是List 不能为空
        delete_ids = request.data.get('ids')
        if not delete_ids:
            return Response(data={'detail': "参数错误，ids为必传参数"}, status=status.HTTP_400_BAD_REQUEST)
        elif not isinstance(delete_ids, list):
            return Response(data={'detail': "ids格式错误必须是List"}, status=status.HTTP_400_BAD_REQUEST)
        MenuModel.objects.filter(id__in=delete_ids).update(delete_flag=1)
        # 删除传递过来的功能菜单
        for m_id in delete_ids:
            MenuModel.objects.filter(parent__id=m_id).update(delete_flag=1)
        # 删除所有的子功能菜单
        return Response(status=status.HTTP_204_NO_CONTENT)
